var appPath = getAppPath();	
var myDomain = 'http://7xogoq.com1.z0.glb.clouddn.com';
var validFile = false;
var uploader = null;

$(function(){
	initJspCompont();
	initJspGrid();
});

function initJspCompont(){
	$("#selctMemberType").combobox({
		url:appPath+'/com/getCodesForCombox.action',
		valueField:'id',
		textField:'text'
	});
}

// 图像缩放
function DrawImage(ImgD,FitWidth,FitHeight){
    var image=new Image();
    image.src=ImgD.src;
    if(image.width>0 && image.height>0){
        if(image.width/image.height>= FitWidth/FitHeight){
            if(image.width>FitWidth){
                ImgD.width=FitWidth;
                ImgD.height=(image.height*FitWidth)/image.width;
            }else{
                ImgD.width=image.width; 
               ImgD.height=image.height;
            }
        } else{
            if(image.height>FitHeight){
                ImgD.height=FitHeight;
                ImgD.width=(image.width*FitHeight)/image.height;
            }else{
                ImgD.width=image.width; 
               ImgD.height=image.height;
            } 
       }
    }
}

// 图片列表初始化
function initJspGrid(){
	
	$('#imageGrid').datagrid({
	    url:appPath + "/itbImg/getImageList.action",
	    height:'full',
	    //remoteSort:false,
	    striped:true,
	    fitColumns:true,
	    queryParams: getQueryParam(),
	    singleSelect:false,
		checkbox:false,
	    frozenColumns:[[
	        {field:'ck',checkbox:'true',width:10,align:'center',sortable:false}/*,
	        {field:'op',title:'操作',width:30,align:'center',sortable:false,
	        	formatter:function(value,rowData,rowIndex){
	        		if(!rowData.img_id) return "";
	        		return "<a href='javascript:void(0)'><img width='12px' height='12px' style='border:0px' src='"+appPath+"/js/lib/jquery-easyui/themes/icons/pencil.png' title='编辑' onClick='showEdit("+rowIndex+")'/></a>";
	        	}
	        }*/
	    ]],
	    columns:[[
	        {field:'img',title:'预览',width:100,align:'center',sortable:false,
	        	formatter:function(url, rowData, rowIndex){
	        		var retUrl = '';
	        		if (rowData.url) {
	        			// '<img src="' + rowData.url + '" onload=javascript:DrawImage(this,160,120); style="height:120px">';
	        			retUrl = '<div style="display:table;text-align:center;height:120px;width:100%">'
	        				+ '<span style="display:table-cell;vertical-align:middle"><img src="'
	        				+ rowData.url+'?x-oss-process=image/resize,m_lfit,h_110,w_130"'
	        				+ 'style="display:inline;max-height:110px;max-width:130px"></span></div>';
	        		}
	        		return retUrl;
	        	}}, 
	        {field:'img_id',title:'图片ID',width:40,align:'center',sortable:true},
	        {field:'img_name',title:'图片名',width:100,align:'left',sortable:true},
	        {field:'url',title:'资源地址',width:270,align:'left',sortable:false,
	        	formatter:function(url, rowData, rowIndex){
	        		var retUrl = '';
	        		if (rowData.url) {
	        			// '<img src="' + rowData.url + '" onload=javascript:DrawImage(this,160,120); style="height:120px">';
	        			retUrl = '<a href="' + rowData.url + '" target="_blank">'
	        				+ rowData.url.replace('https://itbour-back.oss-cn-hangzhou.aliyuncs.com','')
	        				+ '</a>';
	        		}
	        		return retUrl;
	        	}},  
	        {field:'create_time',title:'创建时间',width:90,align:'center',sortable:true}
	    ]],
	    hideColumn:['user_type'],
	    //view: imgView,// 自定义View
	    pagination:true,
		rownumbers:true,
		toolbar:[{
			text:'添加图片',
			iconCls:'icon-add',
			handler:function(){
				showAddInfo();
			}
		},{
			text:'删除图片',
			iconCls:'icon-cancel',
			handler:function(){
				delImage();
			}
		}]
	    
	});

}

function showAdd(){
	$('#selectTypeDlg').dialog({
		buttons:[
			{text:'确定',iconCls:"icon-ok",handler:function(){
				var memberType=$("#selctMemberType").combobox("getValue");
				if(!memberType||memberType.length<=0){
					$.messager.alert('提示信息','请选择会员类型！','warning');
					return;
				}
				$('#selectTypeDlg').dialog('close');
				showAddInfo();
			}},
			{text:'取消',iconCls:"icon-cancel",handler:function(){
				$('#selectTypeDlg').dialog('close');
			}}
		]
	});
	$('#selectTypeDlg').dialog('open');
	//showAddInfo();
}

//重置用户密码
function resetPassword(){
	var selectMember=$("#imageGrid").datagrid("getSelected");
	if(!selectMember){
		$.messager.alert('提示信息','请选择要重置密码的会员！','warning');
		return;
	}
	var url = appPath+"/member/memberInfo_reset.do?memberId="+selectMember.memberId;
	$.post(url,function(data){
		if(data=="ok"){
			$.messager.alert('提示信息','密码重置成功，重置后的密码为123456','info');
		}
	});
}

/**
 * 展现添加图片窗口
 */
function showAddInfo() {
	$("#imgUploadTable").show();
	$('#imgUploadForm').form('clear');
	
	clearUploadList();
	
	$("#submitType").val("save");
	$("#addDlgBtn").show();
	$('#addDlg').window({
		title:'添加图片文件',
		iconCls:'icon-add',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});

	$('#addDlg').window('move',{top:20,left:20});
	$('#addDlg').window('open');
	 
	
	//initUploader();
	initOSS();
}

function isImage(url) {
    var res, suffix = "";
    var imageSuffixes = ["png", "jpg", "jpeg", "gif", "bmp"];
    var suffixMatch = /\.([a-zA-Z0-9]+)(\?|\@|$)/;

    if (!url || !suffixMatch.test(url)) {
        return false;
    }
    res = suffixMatch.exec(url);
    suffix = res[1].toLowerCase();
    for (var i = 0, l = imageSuffixes.length; i < l; i++) {
        if (suffix === imageSuffixes[i]) {
            return true;
        }
    }
    return false;
}

function initUploader() {
	if (uploader) {
		return;
	}
	
	uploader = Qiniu.uploader({
        runtimes: 'html5,flash,html4',
        browse_button: 'pickImgFile',
        //container: 'container',
        //drop_element: 'container',
        max_file_size: '100mb',
        flash_swf_url: appPath + '/js/qiniu/plupload/Moxie.swf',
        dragdrop: false,
        chunk_size: '4mb',
        uptoken_url: appPath+"/itbImg/getUpToken.action",
        //uptoken: data.uptoken,
        domain: myDomain,
        // downtoken_url: '/downtoken',
        // unique_names: true,
        save_key: true,// 自定义文件名
        // x_vars: {
        //     'id': '1234',
        //     'time': function(up, file) {
        //         var time = (new Date()).getTime();
        //         // do something with 'time'
        //         return time;
        //     },
        // },
        auto_start: false,//true
        init: {
            'FilesAdded': function(up, files) {
                $('#uploadMsg').hide();
                
                var fileCnt = up.files.length;
                if (fileCnt > 1) {
                	up.splice(0, fileCnt-1);
                }
                
                var fileName = up.files[0].name;
                $('#imgFileNm').val(fileName);
                if (Qiniu.isImage(fileName)) {
                	validFile = true;
                } else {
                	validFile = false;
                	setMsg("red", "请选择图像文件！");
                }
                
                /*plupload.each(files, function(file) {
                	$('#imgFileNm').val(file.name);
                    var progress = new FileProgress(file, 'fsUploadProgress');
                    progress.setStatus("等待...");
                    progress.bindUploadCancel(up);
                });*/
            },
            'BeforeUpload': function(up, file) {
                /*var progress = new FileProgress(file, 'fsUploadProgress');
                var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
                if (up.runtime === 'html5' && chunk_size) {
                    progress.setChunkProgess(chunk_size);
                }*/
            },
            'UploadProgress': function(up, file) {
            	setMsg("green", file.name + ' 上传中...');
            	
               /* var progress = new FileProgress(file, 'fsUploadProgress');
                var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
                progress.setProgress(file.percent + "%", file.speed, chunk_size);*/
            },
            'UploadComplete': function() {
            	//$('#uploadMsg').show();
            },
            'FileUploaded': function(up, file, info) {
            	var retInfo = $.parseJSON(info);
            	addImage(file.name, myDomain+'/'+ retInfo.key);
            	
            	setMsg("green", file.name + ' 上传成功！');

                /*var progress = new FileProgress(file, 'fsUploadProgress');
                progress.setComplete(up, info);*/

//                $.ajax('./uptoken',{
//                    async: false
//                }).done(function(data){
//                    $.extend(info, data);
//                    progress.setComplete(up, info);
//                }).error(function(){
//                    console.log('获取下载token失败');
//                });

            },
            'Error': function(up, err, errTip) {
            	setMsg("red", errTip);

                var progress = new FileProgress(err.file, 'fsUploadProgress');
                progress.setError();
                progress.setStatus(errTip);
            }
                // ,
                // 'Key': function(up, file) {
                //     var key = "";
                //     // do something with key
                //     return key
                // }
        }
    });
}

/**
 * 删除图片
 */
function delImage(){
	var selectItem=$("#imageGrid").datagrid("getChecked");
	if(!selectItem || selectItem.length == 0){
		$.messager.alert('提示信息','请选择图片','warning');
		return;
	}
	$.messager.confirm("确认", "是否确认删除", function (r) {  
        if (r) { 
			var ids = "";
			$.each(selectItem, function(index, item){
				ids = ids + item.img_id + ",";
			});
			var url = appPath+"/itbImgWeb/deleteImage.action?delIds="+ids;
			$.post(url,function(data){
				if(data=="ok"){
					$.messager.alert('提示信息','删除成功','info');
					doQuery();
				}
			});
        }
	});
}

function addImage(imgNm, imgUrl) {
	var url = appPath+"/itbImgWeb/addImage.action"
	var sendData = {
		"imgInfo.img_name":imgNm,
		"imgInfo.update_by": g_userId || "Unknown",
		"imgInfo.url":imgUrl
	};
    $.post(url, sendData, function(data){  
		if (data == "ok") { 
			doQuery();
        }  
    });
}

/**
 * 开始上传图片
 */
function doPostData(){
	if (validFile && uploader) {
		uploader.start();
	} else {
		setMsg("red", "请选择图像文件！");
	}
}

/**
 * 关闭对话框
 */
function cancelPostData(){
	if (uploader) {
		uploader.destroy();
		uploader = null;
	}
	
	$('#addDlg').window('close');
}

function setMsg(color, msg) {
	$('#msgTxt').css("color", color);
	$('#msgTxt').val(msg);
	$('#uploadMsg').show();
}

/**
 * 获取请求信息
 */
function getQueryParam(){
	var queryObject = {};
	var findUserId = $("#queryUserId").val();
	var findImgName=$("#queryImgName").val();
	if(findUserId&&findUserId.length>0) queryObject.findUserId = findUserId;
	if(findImgName&&findImgName.length>0) queryObject.findImgName = findImgName;
	return queryObject;
}

/**
 * 查询数据
 */
function doQuery(){
	$("#imageGrid").datagrid('unselectAll');
	$("#imageGrid").datagrid('load',getQueryParam());
}

function fmtCreateTime(value, rowData, rowIndex){
	if(!value)return "";
	var s = new Date(value);
	return rowData.create_time=$.DateUtil.format(s,'yyyy/MM/dd hh:mm:ss');
}

function fmtHotFlag(value, rowData, rowIndex){
	if(rowData.hotFlag==1)return "是";
	return "否";
}





// ############### FOR OSS UPLOAD START ###############
//var accessid= '';
//var accesskey= '';
//var uploadHost = 'http://itbour-back.oss-cn-hangzhou.aliyuncs.com';
//var uploadHost = 'https://itbour-back.oss-cn-hangzhou.aliyuncs.com';

var g_object_name = '';
var dtNow = Date.parse(new Date()); //Date.parse(new Date())/1000;

//var policyText = {
//"expiration": "2020-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
//"conditions": [
//  ["content-length-range", 0, 104857600] // 设置上传文件的大小限制
//]
//};
//var policyJsonStr = JSON.stringify(policyText);
//var policyBase64 = Base64.encode(policyJsonStr);
//var message = policyBase64;
//var bytes = Crypto.HMAC(Crypto.SHA1, message, accesskey, { asBytes: true });
//var signature = Crypto.util.bytesToBase64(bytes);

var OSS_PARAM = {
	expire: 0,
	uploadHost: '',
	accessKeyId: '',
	policyBase64: '',
	signature: '',
	flg: false
};

function randomString(len) {
	len = len || 20;
	var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';   
	var maxLen = chars.length;
	var str = '';
	for (var i = 0; i < len; i++) {
		str += chars.charAt(Math.floor(Math.random() * maxLen));
    }
	return str;
}

function getSuffix(filename) {
    var pos = filename.lastIndexOf('.');
    var suffix = '';
    if (pos != -1) {
        suffix = filename.substring(pos);
    }
    return suffix;
}

function calculate_object_name(filename) {
	var now = new Date(); 
	var nowStr = now.format("yyyy/MM/dd/hhmmssS_");
    g_object_name = "image/U"+g_userId+"/"+nowStr + randomString(20);
}

function set_upload_param(up, filename, ret) {
    
	// 判断当前expire是否超过了当前时间,如果超过了则重新取
	dtNow = Date.parse(new Date());//  Date.parse(new Date())/1000
	OSS_PARAM.flg = false;
    if (OSS_PARAM.expire < dtNow + 5000) {// 5s
    	var url = appPath+"/itbImg/getOSSToken.action";
        $.get(url, function(data){  
    		if (data && data.signature) { 
    			OSS_PARAM.expire = data.expire;
    			OSS_PARAM.uploadHost = data.uploadHost;
    			OSS_PARAM.accessKeyId = data.accessKeyId;
    			OSS_PARAM.policyBase64 = data.policyBase64;
    			OSS_PARAM.signature = data.signature;
    			OSS_PARAM.flg = true;
    			
    			doUpStart(up, filename, ret);
            } else {
            	$.messager.alert('提示信息','上传异常, 请重新尝试!','info');
            }  
        });
    } else {
    	doUpStart(up, filename, ret);
    }
}

function doUpStart(up, filename, ret){
	if (filename && filename != '') {
        calculate_object_name(filename);
    }
    var new_multipart_params = {
        'key' : g_object_name,
        'policy': OSS_PARAM.policyBase64,
        'OSSAccessKeyId': OSS_PARAM.accessKeyId, 
        'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
        'signature': OSS_PARAM.signature,
    };

    up.setOption({
        'url': OSS_PARAM.uploadHost,
        'multipart_params': new_multipart_params
    });

    up.start();
}

function clearUploadList() {
	$(".upload_progress_bar").remove();
	$(".upload_progress").remove();
	$(".upload_file_info").remove();
}

function initOSS() {
	if (uploader) {
		return;
	}

	uploader = new plupload.Uploader({
		runtimes : 'html5,flash,silverlight,html4',
		browse_button : 'selFiles', 
	    //multi_selection: false,
		//container: document.getElementById('container'),
		//flash_swf_url : 'lib/plupload-2.1.2/js/Moxie.swf',
		//silverlight_xap_url : 'lib/plupload-2.1.2/js/Moxie.xap',
	    url : 'https://oss.aliyuncs.com',

		init: {
			PostInit: function() {
				document.getElementById('postFiles').onclick = function() {
		            set_upload_param(uploader, '', false);
		            return false;
				};
			},

			FilesAdded: function(up, files) {
				clearUploadList();
				$('#uploadMsg').hide();
				
				var delLen = (up.files.length>=files.length)?(up.files.length-files.length):up.files.length;
				up.splice(0,delLen);
				
				var bAllOk = true;
				plupload.each(files, function(file) {
					if (isImage(file.name)) {
						// add file info list
						document.getElementById('ossfile').innerHTML += 
	                    	'<div id="' + file.id + '" class="upload_file_info">'
	                    	+ file.name + ' (' + plupload.formatSize(file.size) + ') <b></b>'
	                    	+ '<div class="upload_progress">'
	                    	+ '<div class="upload_progress_bar" style="width: 0%">'
	                    	+ '</div></div></div>';
					} else {
						bAllOk = false;
						var ngFile = up.getFile(file.id);
						if (ngFile) {
							up.removeFile(ngFile);
						}
					}
				});
				
				if (!bAllOk) {
					setMsg("red", "已过滤非图像文件！");
				}     
			},

			BeforeUpload: function(up, file) {
	            set_upload_param(up, file.name, true);
	        },

			UploadProgress: function(up, file) {
				var d = document.getElementById(file.id);
				d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
	            var prog = d.getElementsByTagName('div')[0];
				var progBar = prog.getElementsByTagName('div')[0];
				progBar.style.width= 2*file.percent+'px';
				progBar.setAttribute('aria-valuenow', file.percent);
				
				setMsg("green", file.name + ' 上传中...');
			},

			FileUploaded: function(up, file, info) {
	            if (info.status == 200) {
	            	document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '上传成功:' + g_object_name;
	            	addImage(file.name, OSS_PARAM.uploadHost+'/'+ g_object_name);
	            	setMsg("green", '上传成功!');
	            }
	            else {
	            	setMsg("red", '上传出错！');
	            	document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = info.response;
	            }
			},

			Error: function(up, err) {
//				document.getElementById('console').appendChild(document.createTextNode("\nError xml:" + err.response));
				setMsg("red", err.response);
			}
		}
	});
	
	uploader.init();
}
//############### FOR OSS UPLOAD END ###############